<?php

namespace Frieza\Modules\Live\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Doraemon\service\Live\AdmColumn;
use Encore\Admin\Widgets\Form;
use Doraemon\model\Live\LiveColumn as mLiveColumn;
use Doraemon\model\Live\LiveRoom as mLiveRoom;
use Doraemon\model\Live\LiveColumnSubscribe;
use Illuminate\Support\MessageBag;




class ColumnController extends Controller
{
    const PAGE_SIZE = 20;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    public function index(Request $request, Content $content)
    {

        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);

        $where= [];
        if($request->input('name')){
            $where['name~'] = $request->input('name');

        }
        $where['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $where['ORDER'] = ['sort' => 'DESC'];
        $where['column_status'] = mLiveColumn::STATUS_NORMAL;
        $where['is_test'] = mLiveColumn::NOT_TEST;
        $list = AdmColumn::getColumnList($where);

        $result['list'] = $list;
        unset($where['LIMIT']);
        $result['total'] = mLiveColumn::count($where);
        $gridModel = new pGridDataModel($result['list'], $result['total'], [
            'perPage' => $pageSize
        ]);

        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->tools(function ($tools) {
                    $url = url('/admin/live/column/addlivetocolumn');
                    $button = '<div class="btn-group " style="margin-right: 10px">
    <a class="btn btn-sm btn-twitter" title="批量添加栏目直播期数" target="_blank" href="'.$url.'"><i class="fa fa-plus"></i><span class="hidden-xs"> 批量添加栏目直播期数</span></a>
</div>';
                    $tools->append($button);
                });
                $grid->filter(function (Grid\Filter $filter) {
                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('name', '栏目名称');
                    });
                    if (!empty($condition)) {
                        $filter->expand();//默认展开
                    }
                });
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->column('id', 'ID')->width(40);
                $grid->column('column_name', '栏目名称')->width(80);
                $grid->column('column_desc', '描述')->width(100);
                $grid->column('sort', '权重')->editable();
                $grid->column('cover_img', '封面')->image($this->cover_img, 100, 100);
                $grid->column('column_img', '列表图')->image($this->column_img, 100, 100);
                $grid->column('hot', '热度')->width(100);
                $grid->column('total_num', '期数')->display(function() {
                    $display = [];
                    if($this->preview_num){
                        $display[] = "<a href='/admin/live/index?&room_column=$this->id&live_status=0' target='_blank' >未开始:" . $this->preview_num . "</a>";
                    }

                    if($this->living_num){
                        $display[] = "<a href='/admin/live/index?&room_column=$this->id&live_status=1' target='_blank' >直播中:" . $this->living_num . "</a>";
                    }

                    if($this->close_num){
                        $display[] = "<a href='/admin/live/index?&room_column=$this->id&live_status=2' target='_blank' >已结束:" . $this->close_num . "</a>";
                    }
                    return implode("<br>" , $display);
                }
                )->width(100);
                $grid->column('subscribe_num', '订阅人数')->display(function() {
                         $display = [];

                        $display[] = "<a href='/admin/live/column/subscribe/$this->id' target='_blank' >".$this->subscribe_count . "</a>";
                    return implode("<br>" , $display);
                }
                )->width(100);
//                $status = [
//                    'on' => [
//                        'value' => mLiveColumn::NOT_SHOW,
//                        'text' => '是'
//                    ],
//                    'off' => [
//                        'value' => mLiveColumn::IS_SHOW,
//                        'text' => '否'
//                    ],
//                ];
//                $grid->column('is_show', '是否展示')->switchToggle($status);
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableView();
                    $actions->disableDelete();
                });
            }
        );
        $tab = new Tab();
        $tab->add('栏目列表', $gridList->render(), true);
        $tab->addLink('测试栏目列表', url('admin/live/column/test'));
        $tab->addLink('订阅列表', url('admin/live/column/subscribe'));

        return $content->header('栏目列表')->breadcrumb(
            ['text' => '栏目列表'])
            ->row($tab);

    }







    public function test(Request $request, Content $content)
    {

        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);

        $where= [];
        if($request->input('column_name')){
            $where['column_name~'] = $request->input('column_name');

        }
        $where['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $where['ORDER'] = ['sort' => 'DESC'];
        $where['column_status'] = mLiveColumn::STATUS_NORMAL;
        $where['is_test'] = mLiveColumn::IS_TEST;
        $list = AdmColumn::getColumnList($where);

        $result['list'] = $list;
        unset($where['LIMIT']);
        $result['total'] = mLiveColumn::count($where);
        $gridModel = new pGridDataModel($result['list'], $result['total'], [
            'perPage' => $pageSize
        ]);

        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->filter(function (Grid\Filter $filter) {
                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('column_name', '栏目名称');
                    });
                    if (!empty($condition)) {
                        $filter->expand();//默认展开
                    }
                });
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();
                $grid->column('id', 'ID')->width(40);
                $grid->column('column_name', '栏目名称')->width(80);
                $grid->column('column_desc', '描述')->width(100);
//                $grid->column('sort', '权重')->editable();

                $grid->column('cover_img', '封面')->image($this->cover_img, 100, 100);
                $grid->column('hot', '热度')->width(100);
                $grid->column('total_num', '期数')->display(function() {
                    $display = [];
                    if($this->preview_num){
                        $display[] = "<a href='/admin/live/index?&room_column=$this->id&live_status=0' target='_blank' >未开始:" . $this->preview_num . "</a>";
                    }

                    if($this->living_num){
                        $display[] = "<a href='/admin/live/index?&room_column=$this->id&live_status=1' target='_blank' >直播中:" . $this->living_num . "</a>";
                    }

                    if($this->close_num){
                        $display[] = "<a href='/admin/live/index?&room_column=$this->id&live_status=2' target='_blank' >已结束:" . $this->close_num . "</a>";
                    }
                    return implode("<br>" , $display);
                }
                )->width(100);
                $grid->column('subscribe_num', '订阅人数')->display(function() {
                    $display = [];

                    $display[] = "<a href='/admin/live/column/subscribe/$this->id' target='_blank' >".$this->subscribe_count . "</a>";
                    return implode("<br>" , $display);
                }
                )->width(100);
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableView();
                    $actions->disableDelete();
                });
            }
        );
        $tab = new Tab();
        $tab->addLink('栏目列表',  url('admin/live/column'));
        $tab->add('测试栏目列表', $gridList->render(), true);
        $tab->addLink('订阅列表', url('admin/live/column/subscribe'));

        return $content->header('测试栏目列表')->breadcrumb(
            ['text' => '测试栏目列表'])
            ->row($tab);

    }


    /*创建栏目
     *
     * */
    public function create(Request $request, Content $content, $id = 0)
    {
        $header = '添加栏目';
        if ($id) {
            $header = '编辑栏目';
        }
        $info  = $id ? mLiveColumn::getByWhere(['id' => $id] ) :[];

        $form = new Form($info);
        $form->hidden('id');
        $form->text('column_name', '栏目名称');
        $form->textarea('column_desc', '描述');
        $form->number('sort', '权重')->default(0);
        $form->radio('is_show', '是否公开')->options([1 => '公开', 0 => '不公开'])->default(1);
        $form->radio('is_test', '是否测试栏目')->options([ 0 => '非测试',1 => '测试'])->default(0);
        $form->imgUpload('cover_img', '封面图')->help('必传');
        $form->imgUpload('column_img', '列表图')->help('必传');
        $form->action(url('admin/live/column/save'));
        $content->row($form);
        return $content->header($header)->breadcrumb(
            ['text' => '栏目列表', 'url' => url('admin/live/column')],
            ['text' => $header]);
    }


    /*添加成功
     *
     * */
    public function save(Request $request)
    {
        try {
            $params = $request->all();
            $id = isset($params['id']) ? $params['id'] : 0;
            $roomInfo = $id ? mLiveColumn::getByWhere(['id' => $id]) : [];
            $data = [
                'column_name' => $params['column_name'],
                'column_desc' => $params['column_desc'],
                'cover_img' => $params['cover_img'] ? $params['cover_img'] : '',
                'column_img' => $params['column_img'] ? $params['column_img'] : '',
                'column_status' => mLiveColumn::STATUS_NORMAL,
                'sort' => $params['sort'],
                'is_show'  =>$params['is_show'],
                'admin_id' => Admin::user()->id,
                'is_test' => $params['is_test']
            ];
            if (empty($data['column_name'])) {
                throw new \Exception('必须设置栏目名称');
            }
            if (empty($data['column_desc'])) {
                throw new \Exception('必须设置描述');
            }
            if (empty($data['cover_img'])) {
                throw new \Exception('必须上传封面');
            }
            if($id){
                $result = mLiveColumn::updateData($data , ['id' => $id]);
            }else{
               $result =  mLiveColumn::insertData($data);

            }
            if ($result) {
                if($params['is_test']){
                    $url = url('/admin/live/column/test');
                }else{
                    $url = url('/admin/live/column');
                }
                return redirect($url)->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => '操作失败'
                ]);
                return back()->withInput()->with(compact('error'));
            }
        } catch (\Exception $e) {
            Log::debug($e->getMessage(), $e->getFile(), $e->getLine());
            $error = new MessageBag([
                'title' => '操作失败,信息:' . $e->getMessage()
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }



    public function editcolumn(Request $request ,$id)
    {
        try {
            $params = $request->all();
            $data = [
                'admin_id' => Admin::user()->id,
            ];

            if($params['is_show']){
                $data['is_show'] = $params['is_show'] == 'on' ? 1 : 0;
            }
            if($params['column_name'] && $params['value']){
                $data[$params['column_name']] = $params['value'];
            }
            $result = mLiveColumn::updateData($data , ['id' => $id]);
            if ($result) {
                return response()->json([
                    'status' => true,
                    'message' => mLiveColumn::log()
                ]);
            } else {
                throw new \Exception('参数错误或则不存在的直播');
            }
        } catch (\Exception $e) {
            return response()->json(['errors' => [$message = $e->getMessage()]], 422);
        }
    }


    public function deletecolumn(Request $request, $id = 0)
    {
        try {
            if ($id ) {
                mLiveColumn::updateData(['column_status' => mLiveColumn::STATUS_DELETE], ['id' => $id]);
                //取消订阅

                //将room_type 置为空

                return response()->json([
                    'status' => true,
                    'message' => "操作成功",
                ]);

            } else {
                throw new \Exception('不存在的id');
            }
        } catch (\Exception $e) {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
        return response()->json($success);
    }



    public function subscribe(Request $request,Content $content, $column_id = 0)
    {
        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);
        $where= [];
        $extend = [];
        $extend['is_distinct_uid'] =1;
        if($request->input('uid')){
            $where['uid'] = $request->input('uid');
        }
        if($request->input('column_id')){
            $where['column_id'] = $request->input('column_id');
            $extend['is_distinct_uid'] =0;
        }
        $where['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        if($column_id){
            $where['column_id'] = $column_id;
            $extend['is_distinct_uid'] =0;
        }
        $where['subscribe_status'] = mLiveColumn::STATUS_NORMAL;
        $list = AdmColumn::getSubscribeList($where ,$extend);
        $result['list'] = $list;
        if($extend['is_distinct_uid']){
            $result['total'] = LiveColumnSubscribe::countDistinctUid($where);
        }else{
            $result['total'] = LiveColumnSubscribe::count($where);
        }
        $gridModel = new pGridDataModel($result['list'], $result['total'], [
            'perPage' => $pageSize
        ]);

        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->disableCreateButton();
                $grid->paginate($gridModel->getPerPage());
                $grid->filter(function (Grid\Filter $filter) {
                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('column_id', '栏目id');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('uid', 'uid');
                    });
                    if (!empty($condition)) {
                        $filter->expand();//默认展开
                    }
                });
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->column('nick', '昵称')->width(80);
                $grid->column('uid', 'uid')->display(function() {
                      $display = [];
                      $display[] = "<a href='/admin/user/Detail/$this->uid' >".$this->uid . "</a>";
                    return implode("<br>" , $display);
                }
                )->width(100);
                $grid->column('avatar', '头像')->image($this->cover_img, 100, 100);

                $grid->column('subscribe_num', '订阅栏目')->display(function() {
                    $display = [];

                    foreach($this->subscribe_column as $val){
                        $name = $val['column_name'];
                        $display[] = "<a href='/admin/live/column?column_name=$name'  >".$val['column_name'] . "</a>";
                    }
                    return implode("<br>" , $display);
                }
                )->width(500);
                $grid->disableActions();
            }
        );
        $tab = new Tab();
        $tab->addLink('栏目列表', url('admin/live/column'));
        $tab->addLink('测试栏目列表', url('admin/live/column/test'));
        $tab->add('订阅列表', $gridList->render(), true);

        return $content->header('订阅列表')->breadcrumb(
            ['text' => '订阅列表'])
            ->row($tab);
    }


    /*创建栏目
 *
 * */
    public function addLiveToColumn(Request $request, Content $content)
    {
        //直播栏目列表
        $column_list= AdmColumn::columnList();
        $info = [];
        $form = new Form($info);
        $form->select('room_column', '直播栏目')->options($column_list)->required();
        $form->textarea('live_room_id', '直播房间号')->help('房间号间用 英文 "," 隔离');
        $form->action(url('admin/live/column/saveLiveToColumn'));
        $content->row($form);
        return $content->breadcrumb(
            ['text' => '栏目列表', 'url' => url('admin/live/column')]);
    }


    /*添加成功
     *
     * */
    public function saveLiveToColumn(Request $request)
    {
        try {
            $params = $request->all();

            $column_id = isset($params['room_column']) ? $params['room_column'] : 0;
            $ids = isset($params['live_room_id']) ? $params['live_room_id'] : '';

            $room_ids = explode("," , $ids) ? : [];
            if(empty($ids)){
                throw new \Exception('必须设置直播房间号');
            }
            $result =  AdmColumn::addLiveToColumn($column_id , $room_ids);
            if (empty($result)) {
                if($params['is_test']){
                    $url = url('/admin/live/column/test');
                }else{
                    $url = url('/admin/live/column');
                }
                return redirect($url)->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => implode("," , $result)."房间号不存在 , 其余房间已更新"
                ]);
                return back()->withInput()->with(compact('error'));
            }
        } catch (\Exception $e) {
            Log::debug($e->getMessage(), $e->getFile(), $e->getLine());
            $error = new MessageBag([
                'title' => '操作失败,信息:' . $e->getMessage()
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }










}